<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/22 0022
 * Time: 16:31
 */

namespace Cohuna\Services;

use Cohuna\Models\CohunaConfig;

/**
 * 公共服务接口
 * @package Cohuna\Services
 */
class CommonService extends ServiceBase
{
    /**
     * 生成交易单号
     * @param string|null $prefix 前缀
     * @return string
     */
    public function createSerialNumber($prefix = null)
    {
        $key = 'TRANSACTION.SEQUENCE';
        $sequence = $this->redis->incrBy($key,mt_rand(1,9));

        if($sequence > 999999){
            $this->redis->delete($key);
            $sequence = $this->redis->incrBy($key,mt_rand(100,200));
        }
        list($usec, ) = explode(' ', microtime());
        return $prefix . date('YmdHis') .  str_pad(intval($usec * 10000),4,'0') . str_pad($sequence,6,'0',STR_PAD_LEFT);
    }

    /**
     * 创建商户号
     * @return string
     */
    public function createMerchantId()
    {
        $key = 'MERCHANT.SEQUENCE';

        $prefix = 2088;
        $sequence_index = mt_rand(1,3);

        $config = CohunaConfig::findFirstByConfigKey('merchant_sequence');

        if(empty($config) === false){
            $sequence = $this->redis->incrBy($key,$sequence_index);

            list($prefix,$sequence_index) = explode('.',$config->config_value);

            //如果当前数据的值比缓存大，表示缓存的数据被清空过
            if($sequence_index > $sequence){
                $sequence = $this->redis->incrBy($key,$sequence_index);
            }
            if ($sequence >= 1000000000){
                $this->redis->delete($key);
                $sequence = $this->redis->incrBy($key,mt_rand(5,10));
                $prefix++;

            }
            $config->config_value = $prefix .'.'. $sequence;
            $config->save();

        }else{
            $config = new CohunaConfig();
            $sequence = $this->redis->incrBy($key,mt_rand(1,5));
            $config->config_name = '商户号自增序列';
            $config->config_key = 'merchant_sequence';
            $config->config_value = $prefix .'.'. $sequence;
            $config->create();
        }

        return $prefix . str_pad($sequence,10,'0',STR_PAD_LEFT);
    }
}